#ifndef HIGHPRECISIONTIMER_H
#define HIGHPRECISIONTIMER_H

#include <iostream>

#ifdef _WIN32
    #include <Windows.h>
    #define THREAD_MUTEX CRITICAL_SECTION
    #define INIT_MUTEX(x) InitializeCriticalSection(x)
    #define LOCK_MUTEX(x) EnterCriticalSection(x)
    #define UNLOCK_MUTEX(x) LeaveCriticalSection(x)
    #define DESTROY_MUTEX(x) DeleteCriticalSection(x)
    typedef unsigned __int64 uint64_t;
#else
    #include <time.h>
    #include <pthread.h>
    #define THREAD_MUTEX pthread_mutex_t
    #define INIT_MUTEX(x) pthread_mutex_init(x, NULL)
    #define LOCK_MUTEX(x) pthread_mutex_lock(x)
    #define UNLOCK_MUTEX(x) pthread_mutex_unlock(x)
    #define DESTROY_MUTEX(x) pthread_mutex_destroy(x)
    typedef unsigned long long uint64_t;
#endif

class HighPrecisionTimer {
public:
    HighPrecisionTimer();
    ~HighPrecisionTimer();
    
    void start(); // 开始计时
    void stop();  // 停止计时
    
    // 获取花费时间
    uint64_t elapsedNanoSeconds() const;  // 纳秒
    uint64_t elapsedMicroSeconds() const { return elapsedNanoSeconds() / 1000; }  // 微秒
    uint64_t elapsedMilliSeconds() const { return elapsedNanoSeconds() / 1000000; }  // 毫秒
    uint64_t elapsedSeconds() const { return elapsedNanoSeconds() / 1000000000; }  // 秒

private:
    // 时间结构体
    union TimeSpec {
        #ifdef _WIN32
		   LARGE_INTEGER win32;
		#else
           struct timespec posix;
        #endif
    };
	
    TimeSpec m_start;  // 开始时间
    TimeSpec m_end;    // 结束时间
    uint64_t m_freq;   // Windows频率（Linux用1e9代替）
	
    mutable THREAD_MUTEX m_mutex;  // 线程锁
};

#endif